import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:kk/dao/travel_tab_dao.dart';
import 'package:kk/model/travel_model.dart';
import 'package:kk/widget/loading_container.dart';
import 'package:kk/widget/webview.dart';

const TRAVEL_URL =
    "https://m.ctrip.com/restapi/soa2/16189/json/searchTripShootListForHomePageV2?_fxpcqlniredt=09031014111431397988&__gw_appid=99999999&__gw_ver=1.0&__gw_from=10650013707&__gw_platform=H5";
const PAGE_SIZE = 10;

class TravelTabPage extends StatefulWidget {
  final String? travelUrl;
  final String? groupChannelCode;

  const TravelTabPage({Key? key, this.travelUrl, this.groupChannelCode})
      : super(key: key);

  @override
  State<TravelTabPage> createState() => _TravelTabPageState();
}

class _TravelTabPageState extends State<TravelTabPage>
    with AutomaticKeepAliveClientMixin {
  late List<ResultList> travelItems = [];
  int pageIndex = 1;
  bool _loading = true;

  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    _loadData();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadData(loadMore: true);
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LoadingContainer(
          isLoading: _loading,
          child: RefreshIndicator(
              child: MediaQuery.removePadding(
                  removeTop: true,
                  context: context,
                  child: StaggeredGridView.countBuilder(
                      controller: _scrollController,
                      crossAxisCount: 4,
                      itemCount: travelItems.length,
                      itemBuilder: (BuildContext context, int index) =>
                          _TravelItem(
                            index: index,
                            item: travelItems[index],
                          ),
                      staggeredTileBuilder: (int index) =>
                          new StaggeredTile.fit(2))),
              onRefresh: _handleRefresh)),
    );
  }

  void _loadData({loadMore = false}) {
    if (loadMore) {
      pageIndex += 1;
    } else {
      pageIndex = 1;
    }
    TravelTabDao.fetch(widget.travelUrl ?? TRAVEL_URL, widget.groupChannelCode!,
            pageIndex, PAGE_SIZE)
        .then((TravelModel model) {
      setState(() {
        List<ResultList> items = _filterItems(model.resultList!);
        if (travelItems.length > 0) {
          travelItems.addAll(items);
        } else {
          travelItems = items;
        }
        _loading = false;
      });
    }).catchError((e) {
      print(e);
      setState(() {
        _loading = false;
      });
    });
  }

  List<ResultList> _filterItems(List<ResultList> list) {
    if (list == null) {
      return [];
    }
    List<ResultList> filterItems = [];
    list.forEach((item) {
      if (item.article != null) {
        filterItems.add(item);
      }
    });
    return filterItems;
  }

  @override
  bool get wantKeepAlive => true;

  Future<Null> _handleRefresh() async {
    _loadData();
    return null;
  }
}

class _TravelItem extends StatelessWidget {
  final ResultList item;
  final int index;

  const _TravelItem({Key? key, required this.item, required this.index})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        final urls = item.article?.urls;
        if (urls != null && urls.length > 0) {
          String url = "";
          urls.forEach((element) {
            if (element.h5Url != null) {
              url = element.h5Url!;
              return;
            }
          });
          if (url == "" || url == null) return;
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => WebView(
                        url: urls[1].h5Url ?? "",
                        title: "详情",
                      )));
        }
      },
      child: Card(
        child: PhysicalModel(
          color: Colors.transparent,
          clipBehavior: Clip.antiAlias,
          borderRadius: BorderRadius.circular(5),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _itemImage(),
              Container(
                padding: EdgeInsets.all(4),
                child: Text(
                  item.article?.articleTitle ?? "",
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 14, color: Colors.black87),
                ),
              ),
              _infoText()
            ],
          ),
        ),
      ),
    );
  }

  _itemImage() {
    return Stack(
      children: [
        Image.network(
          item.article!.images![0].dynamicUrl ?? "",
        ),
        Positioned(
            left: 8,
            bottom: 8,
            child: Container(
              padding: EdgeInsets.fromLTRB(5, 1, 5, 1),
              decoration: BoxDecoration(
                  color: Colors.black54,
                  borderRadius: BorderRadius.circular(10)),
              child: Row(
                children: [
                  Padding(
                    padding: EdgeInsets.only(right: 3),
                    child: Icon(
                      Icons.location_on,
                      color: Colors.white,
                      size: 12,
                    ),
                  ),
                  LimitedBox(
                    maxWidth: 130,
                    child: Text(
                      _poiName(),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(fontSize: 12, color: Colors.white),
                    ),
                  )
                ],
              ),
            ))
      ],
    );
  }

  String _poiName() {
    final p = item.article?.pois;
    if (p == null || p.length == 0) {
      return "未知";
    }
    return p[0].poiName ?? "未知";
  }

  _infoText() {
    return Container(
      padding: EdgeInsets.fromLTRB(6, 6, 6, 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              PhysicalModel(
                color: Colors.transparent,
                clipBehavior: Clip.antiAlias,
                borderRadius: BorderRadius.circular(12),
                child: Image.network(
                  item.article?.author?.coverImage?.dynamicUrl ?? "",
                  width: 24,
                  height: 24,
                ),
              ),
              Container(
                padding: EdgeInsets.all(5),
                width: 90,
                child: Text(
                  item.article?.author?.nickName ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(fontSize: 12),
                ),
              )
            ],
          ),
          Row(
            children: [
              Icon(
                Icons.thumb_up,
                size: 14,
                color: Colors.grey,
              ),
              Padding(
                padding: EdgeInsets.only(left: 3),
                child: Text(
                  item.article?.likeCount.toString() ?? "",
                  style: TextStyle(fontSize: 10),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}
